/**
* @description: 1011. 在 D 天内送达包裹的能力
* @author hewei
* @date 2022/10/5 14:49
* @version 1.0
*/

public class ShipWithinDays {

    public int shipWithinDays(int[] weights, int days) {
        int r = 0;
        int l = 0;
        for (int weight : weights) {
            l = Math.max(l, weight);
            r += weight;
        }
        while (l < r) {
            int mid = (r - l) / 2 + l;
            if (check(days, weights, mid)) {
                r = mid;
            } else l = mid + 1;
        }
        return l;
    }

    public boolean check(int days, int[] weights, int target) {
        int count = 0;
        int sum = 0;
        for (int weight : weights) {
            sum += weight;
            if (sum > target) {
                sum = weight;
                ++count;
            }
        }
        return count + 1 <= days;
    }
}
